#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
订单解析模块
"""

import os
import re
from typing import Dict, Optional, List


class OrderParser:
    """订单解析类"""
    
    def __init__(self):
        # 状态文件夹定义（顺序与前端表格列顺序一致）
        # 注意：未刻版不需要创建文件夹，因为它检查的是订单根目录
        self.status_folders = ["固态", "未确认", "挂", "已做"]
        
        # 订单文件夹匹配模式
        self.order_pattern = r"^\d+_.+"
    
    def is_order_folder(self, folder_name: str) -> bool:
        """判断是否是订单文件夹"""
        return bool(re.match(self.order_pattern, folder_name))
    
    def is_status_folder(self, folder_name: str) -> bool:
        """判断是否是状态文件夹"""
        return folder_name in self.status_folders
    
    def parse_order_info(self, folder_name: str) -> Optional[Dict[str, str]]:
        """解析订单信息"""
        # 解析格式：101_上海勇灵
        parts = folder_name.split("_", 1)
        if len(parts) == 2:
            return {
                "number": parts[0],
                "customer": parts[1]
            }
        return None
    
    def check_order_status(self, order_path: str) -> Dict[str, any]:
        """检查订单状态"""
        has_files_in_level2 = False
        status_folders = {}
        
        if not os.path.exists(order_path):
            return {
                'has_files_in_level2': False,
                'status_folders': {}
            }
        
        try:
            for item in os.listdir(order_path):
                item_path = os.path.join(order_path, item)
                
                if os.path.isfile(item_path):
                    name_lower = item.lower()
                    _, ext = os.path.splitext(name_lower)
                    if name_lower.startswith('.'):
                        print(f"⚠️ 忽略系统/隐藏文件: {item_path}")
                        continue
                    allowed_extensions = {'.pdf', '.ai', '.cdr'}
                    if ext not in allowed_extensions:
                        print(f"⚠️ 忽略不在统计范围的文件: {item_path}")
                        continue
                    has_files_in_level2 = True
                elif os.path.isdir(item_path) and self.is_status_folder(item):
                    file_count = self._count_files_in_folder(item_path)
                    has_files = file_count > 0
                    status_folders[item] = {
                        'file_count': file_count,
                        'has_files': has_files
                    }
        except (OSError, PermissionError) as e:
            print(f"检查订单状态时出错 {order_path}: {e}")
        
        # 未刻版状态：检查订单目录下是否有文件
        not_engraved_status = {
            'file_count': self._count_files_in_folder(order_path) if has_files_in_level2 else 0,
            'has_files': has_files_in_level2
        }
        
        # 固态状态：检查固态目录下是否有文件
        solid_state_path = os.path.join(order_path, "固态")
        solid_state_status = {
            'file_count': 0,
            'has_files': False
        }
        if os.path.exists(solid_state_path) and os.path.isdir(solid_state_path):
            solid_state_status['file_count'] = self._count_files_in_folder(solid_state_path)
            solid_state_status['has_files'] = solid_state_status['file_count'] > 0
        
        return {
            'has_files_in_level2': has_files_in_level2,
            'status_folders': status_folders,
            'not_engraved': not_engraved_status,  # 添加未刻版状态
            'solid_state': solid_state_status  # 添加固态状态
        }
    
    def _count_files_in_folder(self, folder_path: str) -> int:
        """计算文件夹中的文件数量"""
        try:
            allowed_extensions = {'.pdf', '.ai', '.cdr'}
            return len([
                f for f in os.listdir(folder_path)
                if os.path.isfile(os.path.join(folder_path, f))
                and not f.startswith('.')
                and os.path.splitext(f.lower())[1] in allowed_extensions
            ])
        except (OSError, PermissionError):
            return 0
    
    def create_status_folders(self, order_path: str) -> bool:
        """为订单创建状态文件夹"""
        try:
            if not os.path.exists(order_path):
                print(f"❌ 订单路径不存在: {order_path}")
                return False
            
            created_count = 0
            for folder_name in self.status_folders:
                folder_path = os.path.join(order_path, folder_name)
                if not os.path.exists(folder_path):
                    os.makedirs(folder_path, exist_ok=True)
                    created_count += 1
                    print(f"✅ 创建状态文件夹: {folder_path}")
            
            if created_count > 0:
                print(f"✅ 为订单创建了 {created_count} 个状态文件夹")
            
            return True
        except Exception as e:
            print(f"❌ 创建状态文件夹失败 {order_path}: {e}")
            return False
    
    def get_order_folders(self, base_path: str) -> List[Dict[str, str]]:
        """获取所有订单文件夹信息"""
        order_folders = []
        
        if not os.path.exists(base_path):
            return order_folders
        
        try:
            for item in os.listdir(base_path):
                item_path = os.path.join(base_path, item)
                if os.path.isdir(item_path) and self.is_order_folder(item):
                    order_info = self.parse_order_info(item)
                    if order_info:
                        order_info['path'] = item_path
                        order_info['status'] = self.check_order_status(item_path)
                        order_folders.append(order_info)
        except (OSError, PermissionError) as e:
            print(f"获取订单文件夹时出错 {base_path}: {e}")
        
        return order_folders
    
    def validate_order_data(self, order_data: Dict[str, any]) -> List[str]:
        """验证订单数据"""
        errors = []
        
        # 检查必填字段
        required_fields = ['number', 'customer']
        for field in required_fields:
            if not order_data.get(field):
                errors.append(f"缺少必填字段: {field}")
        
        # 检查订单号格式
        if order_data.get('number') and not re.match(r'^\d+$', str(order_data['number'])):
            errors.append("订单号必须为数字")
        
        # 检查客户名称
        if order_data.get('customer') and len(order_data['customer'].strip()) < 2:
            errors.append("客户名称至少需要2个字符")
        
        # 检查优先级
        valid_priorities = ['低级', '中级', '高级']
        if order_data.get('priority') and order_data['priority'] not in valid_priorities:
            errors.append(f"优先级必须是: {', '.join(valid_priorities)}")
        
        # 检查交货日期
        valid_delivery_dates = ['当天', '明天', '后天', '本周', '下周']
        if order_data.get('delivery_date') and order_data['delivery_date'] not in valid_delivery_dates:
            errors.append(f"交货日期必须是: {', '.join(valid_delivery_dates)}")
        
        return errors
    
    def format_order_summary(self, order: Dict[str, any]) -> str:
        """格式化订单摘要"""
        status_parts = []
        
        if order.get('is_completed'):
            status_parts.append("已完成")
        elif order.get('pending'):
            status_parts.append("待处理")
        elif order.get('not_confirmed'):
            status_parts.append("未确认")
        elif order.get('not_engraved'):
            status_parts.append("未雕刻")
        
        status_text = " | ".join(status_parts) if status_parts else "进行中"
        
        return f"{order.get('number', 'N/A')} - {order.get('customer', 'N/A')} ({status_text})"
    
    def get_status_summary(self, status_data: Dict[str, any]) -> str:
        """获取状态摘要"""
        if not status_data:
            return "无状态信息"
        
        parts = []
        
        if status_data.get('has_files_in_level2'):
            parts.append("有文件")
        
        status_folders = status_data.get('status_folders', {})
        if status_folders:
            folder_info = []
            for folder, count in status_folders.items():
                folder_info.append(f"{folder}({count})")
            parts.append("状态: " + ", ".join(folder_info))
        
        return " | ".join(parts) if parts else "无状态"
